<?php

class AuthController extends Zend_Controller_Action
{

    public function indexAction()
    {
        $request = $this->getRequest();
        $form = new Application_Form_Login();
        $authAdapter = new Zend_Auth_Adapter_DbTable(
            Zend_Db_Table::getDefaultAdapter(),
            'users',
            'username',
            'password',
            'MD5(CONCAT(password_salt, ?))'
        );

        if ($request->isPost() && $form->isValid($request->getPost())) {

            $authAdapter->setIdentity($form->getValue('username'))
                    ->setCredential($form->getValue('password'));

            $result = Zend_Auth::getInstance()->authenticate($authAdapter);

            if ($result->isValid()) {
                $this->_redirect($this->getHelper('url')->url(array(), 'index'));
            } else {
                $form->getElement('password')->addError('Login failed');
            }
        }
        $this->view->form = $form;
    }

    public function logoutAction()
    {
        $request = $this->getRequest();
        $form = new Application_Form_Logout();

        if ($request->isPost() && $form->isValid($request->getPost())) {
            Zend_Auth::getInstance()->clearIdentity();
            $this->_redirect($this->getHelper('url')->url(array(), 'index'));
        }

        $this->view->form = $form;
    }

    public function blockAction()
    {
        $identity = Zend_Auth::getInstance()->getIdentity();
        $this->view->isUserLoggedIn = $identity->isLoggedIn();
        $this->view->username = $identity->getUsername();
        $this->view->token = $identity->getAuthToken();
        if ($identity->isLoggedIn()) {
            $this->view->logoutForm = new Application_Form_Logout();
        } else {
            $this->view->loginForm = new Application_Form_Login();
        }
    }


}





